<?php

namespace App\Http\Controllers;

use  Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * 这里这个构造函数调用了 中间件auth 对我们进行权限认证
 * 即要求我们必须登陆才可以访问该控制器的其他方法
 * 有两种解决方法，一直是在 $this->middleware('auth')->except('你要排除权限认证的方法')，比如 ...->except('index')
 * 另一种是直接干掉这个函数（我们确定这个控制器就只是来展示首页的，那么就干掉它吧）
 */
class CommunityController extends BaseController
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        return view('community/index');
    }

    public function detail()
    {
        return view('community/detail');
    }

    public function drawing()
    {
        return view('community/drawing');
    }

    public function edit()
    {
        return view('community/edit');
    }

    public function save(Request $request)
    {
        $params = $request->all();

        // 数据校验
        $data['name'] = empty($params['name']) ? '' : $params['name'];
        $data['second_name'] = empty($params['second_name']) ? '' : $params['second_name'];
        $data['average_price'] = empty($params['average_price']) ? 0 : $params['average_price'];
        $data['address'] = empty($params['address']) ? '' : $params['address'];
        $data['description'] = empty($params['description']) ? '' : $params['description'];
        $data['remarks'] = empty($params['remarks']) ? '' : $params['remarks'];
        $data['thumb'] = empty($params['thumb']) ? '' : $params['thumb'][0]['id'];
        $data['pics'] = empty($params['pics']) ? '' : getPics($params['pics']);

        if (isset($params['id'])) {
            $id = $params['id'];
            $ret = Db::table('community')->where('id', $params['id'])->update($data);
        } else {
            $data['add_time'] = time();
            $id = $ret = Db::table('community')->insertGetId($data);
        }

        response_json($ret ? 0 : 1, $ret ? '保存成功！' : '保存失败，请联系管理员！', ['id' => $id]);
    }

    public function upload(Request $request)
    {
        if ($request->isMethod('POST')) { //判断文件是否是 POST的方式上传
            $tmp = $request->file('file');

            $path = '/pics'; //public下的pics
            if ($tmp->isValid()) { //判断文件上传是否有效
                $FileType = $tmp->getClientOriginalExtension(); //获取文件后缀
                $realName = $tmp->getClientOriginalName();
                $size = $tmp->getSize();

                $FilePath = $tmp->getRealPath(); //获取文件临时存放位置

                $FileName = date('Y-m-d') . '-' . uniqid() . '.' . $FileType; //定义文件名

                Storage::disk('pics')->put($FileName, file_get_contents($FilePath)); //存储文件

                $id = Db::table('files')->insertGetId([
                    'real_name' => $realName,
                    'size' => $size,
                    'file_name' => $FileName,
                    'url' => $path . '/' . $FileName,
                    'add_time' => time(),
                    'user_id' => 1
                ]);

                response_json($id ? 0 : 1, $id ? '上传成功！' : '上传失败，请联系管理员！', ['id' => $id]);
            }
        }
    }

    public function getOne(Request $request)
    {
        $params = $request->all();
        if (empty($params['id'])) {
            response_json(1, '参数丢失，请联系管理员！');
        }

        // 查询小区详情
        $community = Db::table('community')->where('id', $params['id'])->first();
        $community->thumb = getFile($community->thumb);
        $community->pics = getFile($community->pics);

        // 根据小区id，查询楼栋数据
        $building = Db::table('building')
            ->where('community_id', $params['id'])
            ->get();
        $arr = [];
        for ($i = 1; $i <= 225; $i ++) {
            $arr[$i] = [
                'number' => $i,
                'build_num' => $i,
            ];
        }
        foreach ($building as $row) {
            if (in_array($row->number, range(1, 100))) {
                $arr[$row->number] = $row;
            }
        }

        // 组装数据
        $data = [
            'community' => $community,
            'building' => $arr
        ];

        response_json($community ? 0 : 1, $community ? '' : '地址有误，请联系管理员！', $data);
    }

    public function getList(Request $request)
    {
        $params = $request->all();
        $params['page_size'] = empty($params['page_size']) ? 15 : $params['page_size'];
        $params['current_page'] = empty($params['current_page']) ? 1 : $params['current_page'];
        $params['keywords'] = empty($params['keywords']) ? '' : trim($params['keywords']);

        $where = [['is_del', '=', '0']];
        if (!empty($params['keywords'])) {
            $where[] = ['name', 'like', "%{$params['keywords']}%"];
        }
        $data = DB::table('community')
            ->select('id', 'name', 'address', 'average_price', 'update_time', 'second_name')
            ->where($where)
            ->paginate($params['page_size'], ['*'], 'page', $params['current_page']);

        response_json(0, '', $data);
    }

    public function del(Request $request)
    {
        $params = $request->all();
        if (empty($params['id'])) {
            response_json(1, '参数有误，请联系管理员！');
        }
        $ret = Db::table('community')->where('id', $params['id'])->update(['is_del' => 1]);
        response_json($ret ? 0 : 1, $ret ? '删除成功！' : '删除失败，请联系管理员！');
    }
}
